<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            position: relative;
        }

        img {
            width: 300px;
            padding: 5px;
        }
    </style>
</head>

<body>
    <div class="box">
        <img src="./img/b1.jpg" alt="">
        <img src="./img/b2.jpg" alt="">
        <img src="./img/b3.jpg" alt="">
        <img src="./img/b4.jpg" alt="">
        <img src="./img/b5.jpg" alt="">
        <img src="./img/b6.jpg" alt="">
        <img src="./img/b7.jpg" alt="">
        <img src="./img/b1.jpg alt="">
        <img src="./img/b2.jpg alt="">
        <img src="./img/b3.jpg" alt="">
        <img src="./img/b4.jpg" alt="">
        <img src="./img/b5.jpg" alt="">
        <img src="./img/b6.jpg" alt="">
        <img src="./img/b7.jpg" alt="">
        <img src="./img/jennie.jpeg" alt="">
        <img src="./img/jisoo.jpg" alt="">
        <img src="./img/lalisa.jpg" alt="">
        <img src="./img/rose.jpg" alt="">
        <img src="./img/jisoo.jpg" alt="">

    </div>
</body>
<script>
    window.onload = function () {
        var box = document.querySelector('.box')
        var boxW = box.offsetWidth

        var imgs = document.querySelectorAll('img')
        var imgsW = imgs[0].offsetWidth;

        var num = Math.floor(boxW / imgsW);

        var arrH = [];
        for (var i = 0; i < imgs.length; i++) {
            if (i < num) {
                arrH.push(imgs[i].offsetHeight)
            } else {
                var obj = {
                    minH: arrH[0],
                    minI: 0
                }
                for (let j = 0; j < arrH.length; j++) {
                    if (arrH[j] < obj.minH) {
                        obj.minH = arrH[j];
                        obj.minI = j;
                    }
                }
                imgs[i].style.position = "absolute"
                imgs[i].style.left = imgs[obj.minI].offsetLeft + 'px'
                imgs[i].style.top = obj.minH
                arrH[obj.minI] = arrH[obj.minI]+imgs[i].offsetHeight
            }
        }

    }
</script>

</html>